package com.example.scene;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import org.andengine.engine.camera.hud.HUD;
import org.andengine.engine.handler.IUpdateHandler;
import org.andengine.engine.handler.timer.ITimerCallback;
import org.andengine.engine.handler.timer.TimerHandler;
import org.andengine.entity.IEntity;
import org.andengine.entity.modifier.AlphaModifier;
import org.andengine.entity.modifier.MoveModifier;
import org.andengine.entity.modifier.MoveXModifier;
import org.andengine.entity.modifier.MoveYModifier;
import org.andengine.entity.modifier.ParallelEntityModifier;
import org.andengine.entity.modifier.ScaleModifier;
import org.andengine.entity.modifier.SequenceEntityModifier;
import org.andengine.entity.particle.ParticleSystem;
import org.andengine.entity.particle.SpriteParticleSystem;
import org.andengine.entity.particle.emitter.PointParticleEmitter;
import org.andengine.entity.particle.emitter.RectangleParticleEmitter;
import org.andengine.entity.particle.initializer.VelocityParticleInitializer;
import org.andengine.entity.particle.modifier.AlphaParticleModifier;
import org.andengine.entity.particle.modifier.RotationParticleModifier;
import org.andengine.entity.primitive.Rectangle;
import org.andengine.entity.scene.CameraScene;
import org.andengine.entity.scene.IOnAreaTouchListener;
import org.andengine.entity.scene.ITouchArea;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.scene.menu.MenuScene;
import org.andengine.entity.scene.menu.MenuScene.IOnMenuItemClickListener;
import org.andengine.entity.scene.menu.item.IMenuItem;
import org.andengine.entity.scene.menu.item.SpriteMenuItem;
import org.andengine.entity.scene.menu.item.decorator.ScaleMenuItemDecorator;
import org.andengine.entity.sprite.Sprite;
import org.andengine.entity.sprite.TiledSprite;
import org.andengine.entity.text.Text;
import org.andengine.entity.text.TextOptions;
import org.andengine.extension.physics.box2d.PhysicsConnector;
import org.andengine.extension.physics.box2d.PhysicsFactory;
import org.andengine.extension.physics.box2d.PhysicsWorld;
import org.andengine.ui.activity.BaseGameActivity;
import org.andengine.ui.activity.SimpleBaseGameActivity;
import org.andengine.util.color.Color;
import org.andengine.util.modifier.IModifier;
import org.andengine.util.progress.ProgressCallable;

import ultility.dataString;

import android.content.Loader.ForceLoadContentObserver;
import android.content.SharedPreferences;
import android.hardware.SensorManager;
import android.os.CountDownTimer;
import android.text.style.BulletSpan;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.Toast;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.example.base.BaseScene;
import com.example.fruit.GameActivity;
import com.example.fruit.R;
import com.example.fruitpool.Boom;
import com.example.fruitpool.BoomPool;
import com.example.fruitpool.Fruit;
import com.example.fruitpool.FruitPool;
import com.example.input.Input.TouchEvent;
import com.example.manager.SceneManager;
import com.example.manager.SceneManager.SceneType;
import com.example.touch.MultiTouchHandler;
import com.example.touch.MultiTouchHandlerForTimeMode;

public class TimerMode extends BaseScene implements IOnMenuItemClickListener {
	public Text text,textx2;
	public Text txtTimer;

	public MultiTouchHandlerForTimeMode touch;
	final RectangleParticleEmitter particleEmitter = null;
	final SpriteParticleSystem particleSystem = null;
	public int mIndex = 0;
	public static ArrayList<Fruit> fruitList = new ArrayList<Fruit>();
	public static ArrayList<Fruit> specList = new ArrayList<Fruit>();
	public static ArrayList<Boom> boomList = new ArrayList<Boom>();

	public int fruitCount = 0, boomCount = 0;
	ArrayList<Runnable> arrFruit = new ArrayList<Runnable>();
	ArrayList<Runnable> arrBoom = new ArrayList<Runnable>();

	static int delayFruit = 4000;
	public static String score,scorex2;

	int missScore = 0;
	int missBoom = 0;

	int numMissScore = 3;
	int currentLevel;
	float startTime = System.currentTimeMillis();
	final ArrayList<Thread> A = new ArrayList<Thread>();
	private SharedPreferences audioOptions;
	private SharedPreferences.Editor audioEditor;
	public static boolean isPlay;
	private CameraScene mPauseScene;
	private boolean runningFlag = false;
	private boolean pauseFlag = false;
	
	public TimerMode() {
		runningFlag=true;
		this.registerUpdateHandler(defect);
		score = new String("0");
		scorex2 = new String("0");

	}

	public void setLevel(int i) {
		currentLevel = i;
	}

	public Scene getGameScene() {
		return this;
	}

	public void removeSprite(final Fruit _sprite, Iterator it) {
		activity.runOnUpdateThread(new Runnable() {

			@Override
			public void run() {
				getGameScene().detachChild(_sprite.sprit);
				_sprite.sprit.clearUpdateHandlers();
			}
		});
		it.remove();
	}

	public void removeBoom(final Boom _sprite, Iterator it) {
		activity.runOnUpdateThread(new Runnable() {

			@Override
			public void run() {
				getGameScene().detachChild(_sprite.sprit);
				_sprite.sprit.clearUpdateHandlers();
			}
		});
		it.remove();
	}
	
	public void removeSpecText(final Fruit _sprite, Iterator it) {
		activity.runOnUpdateThread(new Runnable() {

			@Override
			public void run() {
				getGameScene().detachChild(_sprite.spritspec);
				_sprite.spritspec.clearUpdateHandlers();
			}
		});
		it.remove();
	}
	
	public void pauseTimerHandler()
	{
		//time.mPause=true;
		timer.mPause = true;
		timer1.mPause = true;
		timer2.mPause = true;
		timer3.mPause = true;
		timer4.mPause =true;
		timer5.mPause = true;
		timer6.mPause = true;
		timer7.mPause = true;
		timer8.mPause = true;
		timer9.mPause = true;
		timer10.mPause = true;
		timer11.mPause = true;
		timer12.mPause = true;
		timer13.mPause = true;
	}
	IUpdateHandler defect = new IUpdateHandler() {

		@Override
		public void reset() {

		}

		@Override
		public void onUpdate(float pSecondsElapsed) {
			try {
				synchronized (this) {
					// Log.d("update12", "update12");
					/*if (missScore > numMissScore) {
						pauseTimerHandler();
						resetGame("crash");
						getGameScene().setChildScene(cam,false,true,true);
						fruitList.clear();
						boomList.clear();
						clearUpdateHandlers();
						//pauseTimerHandler();
						//SceneManager.getInstance().loadResultScene(engine);
						
					}*/
					// Log.d("update", "update");
					Iterator<Fruit> targets = fruitList.iterator();
					Fruit _target;
					while (targets.hasNext()) {
						_target =  targets.next();
						if (_target.sprit.getY() >= (activity.CAMERA_HEIGHT + 10)) {
							// removeSprite(_target, targets);
							// Log.d("update:", _target.sprit.getX()+"");

							posX++;
							missScore++;
							FruitPool.sharedFruitPool().onHandleRecycleItem(
									_target);
							// targets.remove();
							removeSprite(_target, targets);
							Log.d("missScore", missScore + "");
						}
					}
					Iterator<Boom> booms = boomList.iterator();
					Boom boom;
					// Log.d("update1", "update1");
					// iterating over the targets
					while (booms.hasNext()) {
						boom = booms.next();

						// if target passed the left edge of the screen, then
						// remove it
						// and call a fail
						if (boom.sprit.getY() >= (activity.CAMERA_HEIGHT + 10)) {
							missBoom++;
							BoomPool.sharedBoomPool().onHandleRecycleItem(boom);
							// booms.remove();
							removeBoom(boom, booms);
							// fail();
							// break;
						}
					}
					
					Iterator<Fruit> spectexts = specList.iterator();
					Fruit _spectexts;
					while (spectexts.hasNext()) {
						_spectexts = spectexts.next();

						if (_spectexts.spritspec.getY() >= (activity.CAMERA_HEIGHT +1)
								||_spectexts.spritspec.getX() >= (activity.CAMERA_WIDTH +6)
								||_spectexts.spritspec.getX() < -35) {
							FruitPool.sharedFruitPool().onHandleRecycleItemSpec(_spectexts);
							removeSpecText(_spectexts, spectexts);
						}
					}
					Log.d("sizelist",fruitList.size() + ",boom:" + boomList.size());
					Log.d("sizelistspec",specList.size()+"");
				}

			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	};
	int posX = 1;

	private void ringX(final TiledSprite x1, final float x, final float y) {
		ScaleModifier sMod = new ScaleModifier(0.2f, 1f, 1.6f);
		ScaleModifier sMod1 = new ScaleModifier(0.2f, 1.0f, 0.5f);
		ScaleModifier sMod2 = new ScaleModifier(0.2f, 0.5f, 1f);
		ScaleModifier sMod3 = new ScaleModifier(0.2f, 1f, 1.5f);
		ScaleModifier sMod4 = new ScaleModifier(0.2f, 1.5f, 1.0f);
		ScaleModifier sMod5 = new ScaleModifier(0.2f, 1.6f, 1f);
		float x11 = x;
		float y11 = y;
		MoveModifier mMod = new MoveModifier(0.1f, x11, x11 + 4, y11, y11 + 4);
		MoveModifier mMod1 = new MoveModifier(0.1f, x11, x11 - 4, y11, y11 + 4);
		MoveModifier mMod2 = new MoveModifier(0.1f, x11, x11 + 4, y11, y11 - 4);
		MoveModifier mMod3 = new MoveModifier(0.1f, x11, x11 - 4, y11, y11 - 4);
		MoveModifier mMod4 = new MoveModifier(0.1f, x11, x11 - 3, y11, y11 + 1);
		MoveModifier mMod5 = new MoveModifier(0.1f, x11, x11 + 1, y11, y11 - 4);
		MoveModifier mMod6 = new MoveModifier(0.1f, x11, x11 - 3, y11, y11 - 5);
		MoveModifier mMod7 = new MoveModifier(0.1f, x11, x11 + 1, y11, y11 + 4);

		// MoveModifier mMod4 = new MoveModifier(0.1f, x1.getX(), y, x1.getY(),
		// y);
		x1.registerEntityModifier(new ParallelEntityModifier(
				new SequenceEntityModifier(mMod, mMod1, mMod2, mMod3, mMod4,
						mMod5, mMod6, mMod7), new SequenceEntityModifier(sMod,
						sMod1, sMod2, sMod3, sMod4)));
		registerUpdateHandler(new TimerHandler(1.0f, new ITimerCallback() {

			@Override
			public void onTimePassed(TimerHandler pTimerHandler) {
				x1.setPosition(x, y);
				x1.setCurrentTileIndex(1);
			}
		}));
		// x1.registerEntityModifier(new
		// ParallelEntityModifier(mMod,mMod1,mMod2,mMod3,mMod4,sMod,sMod1,sMod2));
	}

	final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(0f, 0f,
			0f);
	private float[] up = { -SensorManager.GRAVITY_EARTH * 3, -7 * 3f, -5 * 3,
			-3 * 2, -2 * 2, -1 };
	private float[] xRight = { 2f, 2.5f, 3f, 3.5f, 4f, 4.5f };
	private float[] xLeft = { -2f, -2.5f, -3f, -3.5f, -4f, -4.5f };
	PauseableTimerHandler timerstagger;
	int c=0;
	public boolean checkTimer=false;
	private void addFace(final float pX, final float pY, final float pY1,
			final PhysicsWorld mPhysicsWorld, final IsRun isRun,
			final Sprite face, final int side,final float moveX,final float moveY, final float moveX0, final float moveYdown) {
		synchronized (mPhysicsWorld) {
			final float f = (pY - pY1) / 6;

			final Body body = PhysicsFactory.createBoxBody(mPhysicsWorld, face,
					BodyType.DynamicBody, objectFixtureDef);

			mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face,
					body, true, true) {

				@Override
				public void onUpdate(float pSecondsElapsed) {
					synchronized (mPhysicsWorld) {
						super.onUpdate(pSecondsElapsed);
						if (side == 0) {// / left->right
							if (face.getY() > pY1) {
								if (isRun.isRunUp) {
									if(!checkTimer)//neu khong fai la bananacold
										mPhysicsWorld.setGravity(new Vector2(moveX,
												-moveY));
									else //neu la bananacold
										mPhysicsWorld.setGravity(new Vector2(moveX,
												-moveY+10));
								} else {
									if(!checkTimer)//neu khong fai la bananacold
										mPhysicsWorld.setGravity(new Vector2(moveX,
												moveY));
									else //neu la bananacold
										mPhysicsWorld.setGravity(new Vector2(moveX,
												moveY-10));
								}
							}
						} else {
							if (face.getY() > pY1) {
								if (isRun.isRunUp) {
									if(!checkTimer){//neu khong fai la bananacold
										mPhysicsWorld.setGravity(new Vector2(-moveX,
												-moveY));
										Log.d("checkTimer",checkTimer+"");
									}
									else{
										mPhysicsWorld.setGravity(new Vector2(-moveX,
												-moveY+10));
										Log.d("checkTimer",checkTimer+"");
									}
								} else {
									if(!checkTimer){//neu khong fai la bananacold
										mPhysicsWorld.setGravity(new Vector2(-moveX,
												moveY));
										Log.d("checkTimer",checkTimer+"");
									}
									else{
										mPhysicsWorld.setGravity(new Vector2(-moveX,
												moveY-10));
										Log.d("checkTimer",checkTimer+"");
									}
								}
							}

						}
						if (face.getY() < pY1) {
							isRun.isRunUp = false;
								mPhysicsWorld.setGravity(new Vector2(moveX0,
										moveYdown));
							//if(!boomfly)
						
						/*	if(stagger)
							{
								new Runnable() {
									
									@Override
									public void run() {
										// TODO Auto-generated method stub
										int moveX0 = (int) (-5 + Math.random()*10);
										mPhysicsWorld.setGravity(new Vector2(moveX0,
												moveYdown));
										Log.d("moveX0","Runnable");
										if(c==4){
											GameActivity.mHandler.removeCallbacks(this);
											Log.d("moveX0","Runnable1");
										}
										c++;
										try {
											Thread.sleep(200);
										} catch (InterruptedException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
									}
								}.run();
								stagger=false;
							}*/
							
							/*else{
								float t;
								for (int k = 0; k < 3; k++) {
									t= (float) (2+Math.random()*3);
									mPhysicsWorld.setGravity(new Vector2(t, 1));
									try {
										Thread.sleep(333);
									} catch (InterruptedException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
								}
								boomfly=false;
							}*/
						}			
					}
				}
			});
		}
		// face.getX();
	}
	public boolean onAreaTouched( final org.andengine.input.touch.TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea,final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
		if(pSceneTouchEvent.getAction() == MotionEvent.ACTION_DOWN) {
			Log.d("pos", "pause");
		}
		return b;
		}
	/*Sprite pausedSprite;
	Sprite playSprite;
	Sprite restartSprite;
	Sprite quitSprite;
	Sprite titlePauseChildScene;
	*/
	CameraScene cam;
	TiledSprite pausedSprite,restartSprite;
	Sprite quitSprite,titleGame;
	float x,y;
	float xQuit;
	float yQuit;
	Sprite freeze,frenzy,fscorex2;
	@Override
	public void createScene() {
		// this.registerUpdateHandler(defect);
		count_timerTextStagger=new int[20];
		for(int i=0;i<20;i++)
		{
			count_timerTextStagger[i]=0;
		}
		audioOptions = activity.getSharedPreferences("audio",
				activity.MODE_PRIVATE);
		audioEditor = audioOptions.edit();
		mPauseScene = new CameraScene(camera);
		cam = new CameraScene(camera);
		
		Sprite back = new Sprite(0, 0, activity.CAMERA_WIDTH + 1,
				activity.CAMERA_HEIGHT + 1,
				resourcesManager.game_background_region, vbom);
		back.setAlpha(0.5f);
		Sprite backGround = new Sprite(0, 0, activity.CAMERA_WIDTH + 1,
				activity.CAMERA_HEIGHT + 1,
				resourcesManager.game_background_region, vbom);
		backGround.setAlpha(0.5f);
		
		mPauseScene.attachChild(backGround);
		
		//cam
		cam.attachChild(back);
		Text result = new Text(0, 0, resourcesManager.font, "Game Over", vbom);
		final int x1 = (int) (activity.CAMERA_WIDTH / 2 - result.getWidth() / 2);
		final int y1 = (int) (activity.CAMERA_HEIGHT / 2 - result.getHeight() / 2);
		result.setPosition(x1, activity.mCamera.getHeight() + result.getHeight());
		MoveYModifier mod = new MoveYModifier(2, result.getY(), y1) {
			@Override
			protected void onModifierFinished(IEntity pItem) {
				getGameScene().clearChildScene();
				SceneManager.getInstance().loadResultSceneFromTimeMode(engine);
			}
		};
		result.registerEntityModifier(mod);
		cam.attachChild(result);
		cam.setBackgroundEnabled(false);
		
		
		/* Make the label centered on the camera. */
		x = (int) (camera.getWidth() / 2 - resourcesManager.mTiledTextureRegionPlay.getWidth()/2);
		y = (int) (camera.getHeight() / 2 - resourcesManager.mTiledTextureRegionPlay.getHeight() / 2);
		xQuit =  (camera.getWidth()  - (resourcesManager.quitgame_region.getWidth()+10));
		yQuit =  (camera.getHeight() + resourcesManager.quitgame_region.getHeight() );

		 pausedSprite = new TiledSprite(-105, (float)y,100,100, resourcesManager.mTiledTextureRegionPlay, vbom)
		{
			@Override
			public boolean onAreaTouched(
					org.andengine.input.touch.TouchEvent pSceneTouchEvent,
					float pTouchAreaLocalX, float pTouchAreaLocalY) {
				getGameScene().clearChildScene();
				Log.d("pos", "pasdas");
				t.mPause = false;
				timer.mPause = false;
				timer1.mPause = false;
				timer2.mPause = false;
				timer3.mPause =false;
				timer4.mPause = false;
				timer5.mPause =false;
				timer6.mPause = false;
				timer7.mPause = false;
				timer8.mPause =false;
				timer9.mPause = false;
				timer10.mPause = false;
				timer11.mPause = false;
				timer12.mPause = false;
				timer13.mPause = false;
				this.setCurrentTileIndex(1);
				en=0;
		//		backGroundSprite.setAlpha(1f);
				//	engine.start();
				return super
						.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, pTouchAreaLocalY);
			}
		};
		pausedSprite.setCurrentTileIndex(0);
		pausedSprite.setAlpha(0.8f);
		MoveXModifier movex=new MoveXModifier(0.3f, pausedSprite.getX(), camera.getWidth()/2-(pausedSprite.getWidth()+20));
		pausedSprite.registerEntityModifier(movex);
		
		 restartSprite = new TiledSprite(activity.CAMERA_WIDTH+5, y,100,100, resourcesManager.mTiledTextureRegionResume, vbom)
		{
			@Override
			public boolean onAreaTouched(
					org.andengine.input.touch.TouchEvent pSceneTouchEvent,
					float pTouchAreaLocalX, float pTouchAreaLocalY) {
				this.setCurrentTileIndex(1);
				resetGame("restart");
				getGameScene().clearChildScene();
				Log.d("pos", "pasdas");
				return super
						.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, pTouchAreaLocalY);
			}	
		};
		restartSprite.setCurrentTileIndex(0);
		restartSprite.setAlpha(0.8f);
		MoveXModifier movex1=new MoveXModifier(0.3f, restartSprite.getX(), camera.getWidth()/2+20);
		restartSprite.registerEntityModifier(movex1);
		
		 quitSprite = new Sprite(xQuit, yQuit, resourcesManager.quitgame_region, vbom)
		{
			@Override
			public boolean onAreaTouched(
					org.andengine.input.touch.TouchEvent pSceneTouchEvent,
					float pTouchAreaLocalX, float pTouchAreaLocalY) {
				//getGameScene().clearChildScene();
				//Log.d("pos", "pasdas");
				resetGame("quit");
				return super
						.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, pTouchAreaLocalY);
			}
			 
		}; 
		MoveYModifier movex2=new MoveYModifier(0.3f, quitSprite.getY(), camera.getHeight() - (resourcesManager.quitgame_region.getHeight()+10));
		quitSprite.registerEntityModifier(movex2);
		
		
		titleGame = new Sprite(camera.getWidth()/2-resourcesManager.titlepausegame_region.getWidth()/2,-30, resourcesManager.titlepausegame_region, vbom);
		MoveYModifier move3=new MoveYModifier(0.5f, titleGame.getY(), y-100);
		titleGame.registerEntityModifier(move3);
		
		
		mPauseScene.registerTouchArea(pausedSprite);
		mPauseScene.registerTouchArea(restartSprite);
		mPauseScene.registerTouchArea(quitSprite);
		
		mPauseScene.setTouchAreaBindingOnActionDownEnabled(true);
		mPauseScene.setTouchAreaBindingOnActionMoveEnabled(true);
		mPauseScene.attachChild(pausedSprite);
		mPauseScene.attachChild(restartSprite);
		mPauseScene.attachChild(quitSprite);
		mPauseScene.attachChild(titleGame);
		// makes the scene transparent
		mPauseScene.setBackgroundEnabled(false);
		
		
		float startTime = System.currentTimeMillis();
		Log.d("mPhysicsWorld", "mPhysicsWorld");
		FruitPool.prepareManager(resourcesManager, vbom);
		BoomPool.prepareManager(resourcesManager, vbom);
		createBackground();
		createScore();
		// createBoom();
		createFruit();
		createSoundMusicX();
		touch = new MultiTouchHandlerForTimeMode(resourcesManager, vbom, this);
		createTimer();
		// this.registerUpdateHandler(mPhysicsWorld);
		// registerUpdateHandler(defect);
		// Log.d("score","createScene");
		
		//create HUD
		/*HUD hud = new HUD();
		activity.mCamera.setHUD(hud);*/
		
		freeze = new Sprite(resourcesManager.activity.CAMERA_WIDTH
				/ 2 - resourcesManager.freeze_region.getWidth() / 2,-70,150,50,
				resourcesManager.freeze_region, vbom);
		frenzy = new Sprite(resourcesManager.activity.CAMERA_WIDTH
				/ 2 - resourcesManager.frenzy_region.getWidth() / 2,-70,150,50,
				resourcesManager.frenzy_region, vbom);
		
		attachChild(freeze);
		attachChild(frenzy);
	
	}
	int secondTotal = 90;
	final int minute = 0;
	int second;
	public PauseableTimerHandler t;
	private void createTimer() {		
		txtTimer = new Text(0, 0, resourcesManager.font, "1:30", 100, vbom);
		txtTimer.setColor(org.andengine.util.color.Color.GREEN);
		txtTimer.setPosition(605, 10);
		this.attachChild(txtTimer);
		t = new PauseableTimerHandler(1f, true, new ITimerCallback() {
			
			@Override
			public void onTimePassed(TimerHandler pTimerHandler) {
				secondTotal--;//90
				
				if(secondTotal>=60){
					second = secondTotal-60;
					txtTimer.setText("1 :"+second);
				}else if(secondTotal<=9){
					txtTimer.setText("0:0"+secondTotal);					
				}
				else
				txtTimer.setText("0:"+secondTotal);
				if(secondTotal==0){
					//t.mPause = true;
					//t = null;
					engine.unregisterUpdateHandler(t);					
					clearUpdateHandlers();
					pauseTimerHandler();
					resetGame("finish");
					getGameScene().setChildScene(cam, false, true, true);
					fruitList.clear();
					boomList.clear();
					specList.clear();
				}
			}
		});
		engine.registerUpdateHandler(t);
	}

	public void resetGame(String string) {
		if(string.equals("restart")||string.equals("quit"))
			 score = "0";
		 posX = 1;
		 //t.reset();
		timer.reset();
		timer1.reset();
		timer2.reset();
		timer3.reset();
		timer4.reset();
		timer5.reset();
		timer6.reset();
		timer7.reset();
		timer8.reset();
		timer9.reset();
		timer10.reset();
		timer11.reset();
		timer12.reset();
		timer13.reset();
		// t = null;
		 //time=null;
		 timer =null;
		 timer1 = null;
		 timer2 =null;
		 timer3 =null;
		 timer4 =null;
		 timer5 =	 null;
		 timer6 =null;
		 timer7 =null;
		 timer8 =null;
		 timer9 =null;
		 timer10=null;
		timer11=null;
		timer12=null;
		timer13= null;

		 engine.unregisterUpdateHandler(timer);
		 engine.unregisterUpdateHandler(timer1);
		 engine.unregisterUpdateHandler(timer2);
		 engine.unregisterUpdateHandler(timer3);
		 engine.unregisterUpdateHandler(timer4);
		 engine.unregisterUpdateHandler(timer5);
		 engine.unregisterUpdateHandler(timer6);
		 engine.unregisterUpdateHandler(timer7);
		 engine.unregisterUpdateHandler(timer8);
		 engine.unregisterUpdateHandler(timer9);
		 engine.unregisterUpdateHandler(timer10);
		 engine.unregisterUpdateHandler(timer11);
		 engine.unregisterUpdateHandler(timer12);
		 engine.unregisterUpdateHandler(timer13);
		 //RunLevelById(1);
		 if(string.equalsIgnoreCase("quit")){
			 SceneManager.getInstance().loadMenuSceneFromTimeMode(engine);
		 }
		 if(string.equalsIgnoreCase("restart"))
			 SceneManager.getInstance().loadTimerMode(engine);
	}
	boolean b = false;
	
	TimerHandler boomTimerHandler;
	private void createBoom() {
	}

	final ArrayList<Runnable> B = new ArrayList<Runnable>();
	TimerHandler textTimerHandler;

	private void createFruit() {
		RunLevelById(1);
	}
	public static boolean isContinuos = false;
	public static boolean isTwoSide = false;
	public static boolean isRunning = true;

	PauseableTimerHandler timer,timer1,timer2,timer3,timer4,timer5,timer6,timer7,timer8,timer9,timer10,timer11,timer12,timer13;
	private void RunLevelById(int i) {

		final float[] delays = dataString.convertStringToFloat(activity.getResources()
				.getStringArray(R.array.timemodedelay));
		final float[] periods = dataString.convertStringToFloat(activity.getResources()
				.getStringArray(R.array.timemodeperiod));

		 for(int j=0;j<14;j++)
		 {
			 Log.d("tiii",delays[j]+":"+periods[j]);
		 }
		 timer = new PauseableTimerHandler(delays[0], true, new ITimerCallback() {
			
			@Override
			public void onTimePassed(TimerHandler pTimerHandler) {
				if (!isStopped) {
					Log.d("pos","timer is running");
					isContinuos = false;
					int id= (int) (Math.random()*3);
					runGroupText(id);
					runGroupText(0);
					timer.setTimerSeconds(periods[0]);
					count++;
					if (count == 8) {//2
						addSpec(id);
						runGroupText(0);
						runGroupBoom(0);
						//engine.unregisterUpdateHandler(timer);
					//	timer.setTimerCallbackTriggered(true);
						timer.setAutoReset(false);
					}
				}			
			}
		});
		 
		engine.registerUpdateHandler(timer);
		
		timer1 = new PauseableTimerHandler(delays[1], true, new ITimerCallback() {
			
			@Override
			public void onTimePassed(TimerHandler pTimerHandler) {
				if (!isStopped) {
					Log.d("pos","timer1 is running");
					isContinuos = false;
					int id= (int) (Math.random()*2);
					runGroupText(id);
					timer1.setTimerSeconds(periods[1]);
					count1++;
					if (count1 == 3) {//2
						id= (int) (Math.random()*3);
						runGroupText(0);
						addSpec(id);
						//engine.unregisterUpdateHandler(timer1);
						//timer1.setTimerCallbackTriggered(true);
						timer1.setAutoReset(false);
					}
				}
			}
		});
		engine.registerUpdateHandler(timer1);
		timer2 = new PauseableTimerHandler(delays[2], true, new ITimerCallback() {
			
			@Override
			public void onTimePassed(TimerHandler pTimerHandler) {
				if (!isStopped) {
					Log.d("pos","timer2 is running");
					isContinuos = false;
					int id= (int) (1+Math.random()*2);
					runGroupText(id);
					timer2.setTimerSeconds(periods[2]);
					count2++;
					if (count2 == 1) {//2
						id= (int) (Math.random()*2);
						runGroupBoom(id);
						timer2.setAutoReset(false);
					}
				}
			}
		});
		engine.registerUpdateHandler(timer2);
		
		timer3 = new PauseableTimerHandler(delays[3], true, new ITimerCallback() {
			
			@Override
			public void onTimePassed(TimerHandler pTimerHandler) {
				if (!isStopped) {
					Log.d("pos","timer3 is running");
					isContinuos = true;
					float rangX= (float) (15 + Math.random()*5f);
					final float moveX= rangX;
				    final float moveXdown = moveX-10;
					final float moveY= 5;
					final float scale_EARTH=4;
					addTextTwoBound(moveX, moveY,moveXdown,scale_EARTH);
					Log.d("setTimerSeconds","11");
					//runGroupText(3);
					//delay3 += period3;
					Log.d("pos",periods[3]+"");
					timer3.setTimerSeconds(periods[3]);
					count3++;
					if (count3 == 20) {//6
						int id= (int) (Math.random()*2);
						runGroupBoom(id);
						addSpec(id);
						//engine.unregisterUpdateHandler(timer3);
						//timer3.setTimerCallbackTriggered(true);
						timer3.setAutoReset(false);
					}
				}
				Log.d("setTimerSeconds","13");
			}
		});
		engine.registerUpdateHandler(timer3);
		
		timer4 = new PauseableTimerHandler(delays[4], true, new ITimerCallback() {
			
			@Override
			public void onTimePassed(TimerHandler pTimerHandler) {
				if (!isStopped) {
					Log.d("pos","timer4 is running");
					isContinuos = false;
					runGroupText(0);
					//delay4 += period4;
					timer4.setTimerSeconds(periods[4]);
					count4++;
					if (count4 == 6){//2

						//engine.unregisterUpdateHandler(timer4);
						//timer4.setTimerCallbackTriggered(true);
						timer4.setAutoReset(false);
					}
				}
			}
		});
		engine.registerUpdateHandler(timer4);
		
		timer5 = new PauseableTimerHandler(delays[5], true, new ITimerCallback() {
			
			@Override
			public void onTimePassed(TimerHandler pTimerHandler) {
				if (!isStopped) {
					Log.d("pos","timer5 is running");
					isContinuos = false;
					if (count5 == 0) {
						int id= (int) (Math.random()*2);
						runGroupText(id);
					}
					if (count5 == 1) {
						int id= (int) (1+Math.random()*2);
						runGroupText(id);
						runGroupBoom(id-1);
					}
					if (count5 == 2) {
						int id= (int) (Math.random()*2);
						runGroupText(id);
					}
					//delay5 += period5;
					timer5.setTimerSeconds(periods[5]);
					count5++;
					if (count5 == 2){//3
						addSpec(3);
						timer5.setAutoReset(false);
					}
				}
			}
		});
		engine.registerUpdateHandler(timer5);
		final int co1= (int) (8 + Math.random()*3);
		timer6 = new PauseableTimerHandler(delays[6], true, new ITimerCallback() {
			
			@Override
			public void onTimePassed(TimerHandler pTimerHandler) {
				if (!isStopped) {
					Log.d("pos","timer6 is running");
					addTwoSideText();
					addTwoSideText();
					timer6.setTimerSeconds(periods[6]);
					count6++;
					if (count6 == co1) {//7
						addSpec(4);
						//engine.unregisterUpdateHandler(timer6);
						//timer6.setTimerCallbackTriggered(true);
						timer6.setAutoReset(false);
					}
				}
			}
		});
		engine.registerUpdateHandler(timer6);
		timer7 = new PauseableTimerHandler(delays[7], true, new ITimerCallback() {
			
			@Override
			public void onTimePassed(TimerHandler pTimerHandler) {
				if (!isStopped) {
					Log.d("pos","timer7 is running");
					isContinuos = true;
					addTextCorner();
					timer7.setTimerSeconds(periods[7]);
					count7++;
					if (count7 == 14) {//7
						timer7.setAutoReset(false);
					}
			}
			}
		});
		engine.registerUpdateHandler(timer7);
		int r = (int) (1 + Math.random() * 5);
		timer8 = new PauseableTimerHandler(delays[8], true, new ITimerCallback() {
			
			@Override
			public void onTimePassed(TimerHandler pTimerHandler) {
				if (!isStopped) {
					Log.d("pos", "timer8 is running");
					int r = (int) (1 + Math.random() * 5);
					addText();
					timer8.setTimerSeconds(periods[8]);
					count8++;
					if (count8 == r)// 2
					{
						timer8.setAutoReset(false);
					}
				}
			}
		});
		engine.registerUpdateHandler(timer8);
		
		timer9 = new PauseableTimerHandler(delays[9], true, new ITimerCallback() {
			
			@Override
			public void onTimePassed(TimerHandler pTimerHandler) {
				if (!isStopped) {
					Log.d("pos","timer9 is running");
					isContinuos = false;
					int id=(int) (1+Math.random()*2);
					runGroupText(id);
					id=(int) Math.random()+1;
					runGroupBoom(id);
/*					id=(int) (Math.random()*2);
					runGroupText(id);*/
					timer9.setTimerSeconds(periods[9]);
					count9++;
					if (count9 == 4) {//5
						addSpec(3);
						timer9.setAutoReset(false);
					}
				}
			}
		}); 
		engine.registerUpdateHandler(timer9);
		
		final int r1= (int) (7+Math.random()*4);
		timer10 = new PauseableTimerHandler(delays[10], true, new ITimerCallback() {
			
			@Override
			public void onTimePassed(TimerHandler pTimerHandler) {
				if (!isStopped) {
					Log.d("pos","timer10 is running");
					int id=(int) (Math.random()*3);
					runGroupText(id);
					timer10.setTimerSeconds(periods[10]);
					if(r1 > 7)
						periods[10]=0.6f;
					count10++;
					if (count10 == r1) {//5
						addSpec(3);
						timer10.setAutoReset(false);
					}
				}
			}
		}); 
		engine.registerUpdateHandler(timer10);
		
		timer11 = new PauseableTimerHandler(delays[11], true, new ITimerCallback() {
			
			@Override
			public void onTimePassed(TimerHandler pTimerHandler) {
				if (!isStopped) {
					Log.d("pos","timer11 is running");
					runGroupText(0);
					timer11.setTimerSeconds(periods[11]);
					count11++;
					if (count11 >3) {//5
						int id = (int) (2 + Math.random()*2);
						int ids=(int) (Math.random()+3);
						addSpec(ids);
						runGroupText(id);
					}
					if (count11 == 7) {//5
						timer11.setAutoReset(false);
					}
				}
			}
		}); 
		engine.registerUpdateHandler(timer11);
		
		timer12 = new PauseableTimerHandler(delays[12], true, new ITimerCallback() {
			
			@Override
			public void onTimePassed(TimerHandler pTimerHandler) {
				if (!isStopped) {
					Log.d("pos","timer12 is running");
					isContinuos = false;
					runGroupText(0);
					timer12.setTimerSeconds(periods[12]);
					count12++;
					if (count12 == 4) {//5
						
						timer12.setAutoReset(false);
					}
				}
			}
		}); 
		engine.registerUpdateHandler(timer12);
		
		final int r2=(int) (2+Math.random()*2);
		final int co=(int) (7+Math.random()*5);
		timer13 = new PauseableTimerHandler(delays[13], true, new ITimerCallback() {
			
			@Override
			public void onTimePassed(TimerHandler pTimerHandler) {
				if (!isStopped) {
					Log.d("pos","timer13 is running");
					int id= (int) (Math.random()*r2);
					if(count13<4)
						runGroupText(0);
					else
						runGroupText(id);
					timer13.setTimerSeconds(periods[13]);
					count13++;
					if (count13 == co) {//5
						id= (int) (Math.random()*4);
						addSpec(id);
						timer13.setAutoReset(false);
					}
				}
			}
		}); 
		engine.registerUpdateHandler(timer13);
	
	}
	public void runGroupText(int id){
		int k=0;
		switch(id)
		{
			case 0://nem lien tuc mot trai
				addText();
				break;
			case 1://nem lien tuc hai trai
				k=0;
				while (k++<2) {
					addText();
				}
				break;
			case 2://nem lien tuc ba trai
				k=0;
				while (k++<3) {
					addText();
				}
				break;
			case 3://nem lien tuc hai ben
				k=0;
				while (k++<4) {
					addText();
				}
				break;
			case 4://nem lien tuc mot trai
				k=0;
				while (k++<2) {
					addTwoSideText();
				}
				break;
			case 6://nem lien tuc mot trai
				addText();
				break;
			case 7://nem lien tuc mot trai
				addText();
				break;
		}
	}
	public boolean boomfly=false;
	public void runGroupBoom(int id){
		int k=0;
		switch(id)
		{
			case 0://nem lien tuc mot trai
				addSpec(4);
				//addBoom();
				break;
			case 1://nem lien tuc hai trai
				k=0;
				while (k++<2) {
					addSpec(4);
					//addBoom();
				}
				break;
			case 2://nem lien tuc ba trai
				k=0;
				while (k++<3) {
					addSpec(4);
					//addBoom();
				}
				break;
			case 3:
				boomfly=true;
				break;
		}
	}

	boolean stagger=false;

	public void addSpec(int id) {
		Log.d("addText", "addText");
		if (id != 4) {
			int Min = activity.CAMERA_HEIGHT / 4, Max = activity.CAMERA_HEIGHT / 2;

			int k = activity.CAMERA_WIDTH;
			float r = (float) Math.random();
			int x1 = (int) ((r < 0.33f) ? -30: (r >= 0.33f && r <= 0.66) ? activity.CAMERA_WIDTH + 3 : k/ 3 + Math.random() * (k / 3 + 1));
			int y1 = (int) (((r < 0.33f) || (r >= 0.33f && r <= 0.66)) ? Math.random() * activity.CAMERA_HEIGHT / 3 : -30);
			Log.d("wwwwww",x1+"");
			int y0 = activity.CAMERA_HEIGHT;
			float rangX = (float) (15 + Math.random() * 5f);
			final float moveX = rangX;
			float moveYdown = moveX - 6;
			float moveX0 = rangX;
			final float moveY = SensorManager.GRAVITY_EARTH;
			float scale_EARTH = 4;

			final Fruit fruit;
			if (id == 0)
				fruit = FruitPool.sharedFruitPool().onAllocatePoolItemSpec(
						resourcesManager.bananacold_region, "0");
			else if (id == 1)
				fruit = FruitPool.sharedFruitPool().onAllocatePoolItemSpec(
						resourcesManager.bananafrenzy_region, "1");
			else if (id == 2)
				fruit = FruitPool.sharedFruitPool().onAllocatePoolItemSpec(
						resourcesManager.bananax2_region, "2");
			else //3
				fruit = FruitPool.sharedFruitPool().onAllocatePoolItemSpec(
						resourcesManager.boomspec_region, "3");
			fruit.spritspec.setPosition(x1, y1);

			fruit.spritspec.setVisible(true);
			fruit.spritspec.detachSelf();
			attachChild(fruit.spritspec);
			{
				specList.add(fruit);
			}
			fruitCount++;

			mPhysicsWorld = new PhysicsWorld(new Vector2(0, 0), false);
			registerUpdateHandler(mPhysicsWorld);
			IsRun i = new IsRun();
			i.isRunUp = true;
			if (x1 < 0) {
				addFace(x1, y1, y0, mPhysicsWorld, i, fruit.spritspec, 0,
						moveX, moveY, moveX0, moveYdown); // left->right
			} else if (x1 > activity.CAMERA_WIDTH) {
				addFace(x1, y1, y0, mPhysicsWorld, i, fruit.spritspec, 1,
						moveX, moveY, -moveX0, moveYdown);// right->left
			} else {
				moveX0 = 0;
				addFace(x1, y1, y0, mPhysicsWorld, i, fruit.spritspec, 1,
						moveX, moveY, moveX0, moveYdown);// right->left

			}
		} else {
			addBoom();
		}
	}
	public void addBoom() {
		//resourcesManager.sliceWind.play();
		resourcesManager.playSoundWind();
		int maxX = activity.CAMERA_WIDTH/3*2-30;
		int minX = activity.CAMERA_WIDTH/3;
		int x1 = (int) (minX +Math.random()*((maxX-minX)+1));
		int y1 = activity.CAMERA_HEIGHT + 5;

		int maxY = activity.CAMERA_HEIGHT/2;
		int minY = activity.CAMERA_HEIGHT/4+30;
		int y0 = (int) (minY +Math.random()*((maxY-minX)+1));
		
		float rangX=(float) Math.random();
		float moveX= (rangX<0.4) ? 0.0f : rangX + 2f;
		float moveY =  SensorManager.GRAVITY_EARTH;
		float moveYdown =  SensorManager.GRAVITY_EARTH*4;
		float moveX0=0;
		final Boom boom;
		boom = BoomPool.sharedBoomPool().onAllocatePoolItem();
		boom.sprit.setPosition(x1, y1);

		boom.sprit.setVisible(true);
		boom.sprit.detachSelf();
		attachChild(boom.sprit);
		
	
		mPhysicsWorld = new PhysicsWorld(new Vector2(0,
				-SensorManager.GRAVITY_EARTH), false);
		registerUpdateHandler(mPhysicsWorld);
		IsRun i = new IsRun();
		i.isRunUp = true;
		if (x1 <= activity.CAMERA_WIDTH / 2) {
			addFace(x1, y1, y0, mPhysicsWorld, i, boom.sprit, 0,moveX,moveY,moveX0,moveYdown); // left->right
			// side=0
		} else {
			addFace(x1, y1, y0, mPhysicsWorld, i, boom.sprit, 1,moveX,moveY,moveX0,moveYdown);// right->left
			// side=1
		}
		synchronized (boomList) {
			boomList.add(boom);
		}
		boomCount++;
		Log.d("boom", "addText");
	}
	boolean sideTwo2=true;
	public void addTextCorner() {
		Log.d("addText", "addText");
		float r = (float) Math.random();
		int x1 = (r < 0.5f) ? -30 : activity.CAMERA_WIDTH + 3 ;
		if(sideTwo2){
			x1 = -30;
			sideTwo2=false;
		}else{
			x1=activity.CAMERA_WIDTH + 3 ;
			sideTwo2=true;
		}
		
		int y1 = (int) (-20 + Math.random()*41);
		int y0 = activity.CAMERA_HEIGHT;
		
		float rangX = (float) (10 + Math.random() * 5f);
		final float moveX = rangX;
		float moveYdown = moveX - 6;
		float moveX0 = rangX;
		final float moveY = SensorManager.GRAVITY_EARTH;
		float scale_EARTH = 4;

		final Fruit fruit;
		fruit=FruitPool.sharedFruitPool().onAllocatePoolItem();
		fruit.sprit.setPosition(x1, y1);

		fruit.sprit.setVisible(true);
		fruit.sprit.detachSelf();
		attachChild(fruit.sprit);
		{
			fruitList.add(fruit);
		}
		fruitCount++;
		
		mPhysicsWorld = new PhysicsWorld(new Vector2(0,
				0), false);
		registerUpdateHandler(mPhysicsWorld); 
		IsRun i = new IsRun();
		i.isRunUp = true;
		if (x1 < 0) {
			addFace(x1, y1, y0, mPhysicsWorld, i, fruit.sprit, 0, moveX,
					moveY,moveX0, moveYdown); // left->right
		} else if (x1 > activity.CAMERA_WIDTH) {
			addFace(x1, y1, y0, mPhysicsWorld, i, fruit.sprit, 1, moveX,
					moveY,-moveX0, moveYdown);// right->left
		}

	}
	public int yContinue,kl=0;
	public boolean sideTwo1=true;
	public void addTextTwoBound(float moveX,float moveY,float moveXdown, float scale_EARTH)
	{
		resourcesManager.playSoundWind();
		int Min=activity.CAMERA_HEIGHT/4,Max=activity.CAMERA_HEIGHT/2;
		int x1,y1;
		if(sideTwo1){
			x1=-30;
			if(kl==0)
				yContinue = y1 = Min + (int)(Math.random() * ((Max - Min) + 1));
			else
				y1=yContinue;
			kl++;
			sideTwo1=false;
		}
		else{
			x1=activity.CAMERA_WIDTH+4;
			if(kl==0)
				yContinue = y1 = Min + (int)(Math.random() * ((Max - Min) + 1));
			else
				y1=yContinue;
			kl++;
			sideTwo1=true;
		}
		int y0=y1-activity.CAMERA_HEIGHT/8;
		final Fruit fruit;
		fruit = FruitPool.sharedFruitPool().onAllocatePoolItem();
		fruit.sprit.setPosition(x1, y1);

		// target.setVisible(true);
		// target.detachSelf();
		fruit.sprit.setVisible(true);
		fruit.sprit.detachSelf();
		attachChild(fruit.sprit);
		{
			fruitList.add(fruit);
		}
		fruitCount++;
		mPhysicsWorld = new PhysicsWorld(new Vector2(10,
				-SensorManager.GRAVITY_EARTH), false);
		// synchronized (mPhysicsWorld)
		registerUpdateHandler(mPhysicsWorld); // side=0
		IsRun i = new IsRun();
		i.isRunUp = true;
		if (x1 <0) {
			addFaceTwoBound(x1, y1, y0, mPhysicsWorld, i, fruit.sprit, 0, moveX, moveY,moveXdown,scale_EARTH);
		} else {
			addFaceTwoBound(x1, y1, y0, mPhysicsWorld, i, fruit.sprit, 1, moveX, moveY,moveXdown,scale_EARTH);

		}
		Log.d("tao",sideTwo1+"");
		
	}
	private void addFaceTwoBound(final float pX, final float pY,final float pY1,
			final PhysicsWorld mPhysicsWorld, final IsRun isRun,
			final Sprite face, final int side,final float moveX, final float moveY,final float moveXdown,final float scale_EARTH) {
		synchronized (mPhysicsWorld) {
			
			final Body body = PhysicsFactory.createBoxBody(mPhysicsWorld, face,
					BodyType.DynamicBody, objectFixtureDef);
			
			mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face,
					body, true, true) {

				@Override
				public void onUpdate(float pSecondsElapsed) {
					synchronized (mPhysicsWorld) {
						super.onUpdate(pSecondsElapsed);
						if (side == 0) {// / left->right
							if (face.getY() > pY1) {
								if (isRun.isRunUp) {
									if(!checkTimer)
										mPhysicsWorld.setGravity(new Vector2(moveX,
												-moveY));
									else //neu la bananacold
										mPhysicsWorld.setGravity(new Vector2(moveX-8,
												-moveY));
								} else {
									if(!checkTimer)
										mPhysicsWorld.setGravity(new Vector2(moveX,
												SensorManager.GRAVITY_EARTH*scale_EARTH));
									else
										mPhysicsWorld.setGravity(new Vector2(moveX-8,
												SensorManager.GRAVITY_EARTH));
								}
							}							
						}else{
							if (face.getY() > pY1) {
								if (isRun.isRunUp) {
									if(!checkTimer)
										mPhysicsWorld.setGravity(new Vector2(-moveX,
												-moveY));
									else
										mPhysicsWorld.setGravity(new Vector2(-moveX+8,
												-moveY));
								} else {
									if(!checkTimer)
										mPhysicsWorld.setGravity(new Vector2(-moveX,
												SensorManager.GRAVITY_EARTH*scale_EARTH));
									else
										mPhysicsWorld.setGravity(new Vector2(-moveX+8,
												SensorManager.GRAVITY_EARTH));
								}
							}	
						}
						if (face.getY() < pY1) {
							isRun.isRunUp = false;
							mPhysicsWorld.setGravity(new Vector2(0,
									SensorManager.GRAVITY_EARTH*8));
						}	
					}
				}
			});
		}
		// face.getX();
	}
	int count = 0;
	int count1 = 0;
	int count2 = 0;
	int count3 = 0;
	int count4 = 0;
	int count5 = 0;

	int count6 = 0;
	int count8 = 0;
	int count7 = 0;
	int count9 = 0;
	
	int count10 = 0;
	int count11 = 0;
	int count12 = 0;
	int count13 = 0;
	public boolean isStopped = false;
	public boolean endingLevel = false;
	private void createSoundMusicX() {
		if (audioOptions.getBoolean("musicOn", true)) {
			index = 0;
		} else {
			index = 1;
		}
		if (audioOptions.getBoolean("effectsOn", true)) {
			indexS = 0;
		} else {
			indexS = 1;
		}
		music = new TiledSprite(530, 13, 50, 40,
				resourcesManager.mTiledTextureRegionMusic, vbom) {
			@Override
			public boolean onAreaTouched(
					final org.andengine.input.touch.TouchEvent pAreaTouchEvent,
					final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
				switch (pAreaTouchEvent.getAction()) {
				case org.andengine.input.touch.TouchEvent.ACTION_DOWN:
					break;
				case org.andengine.input.touch.TouchEvent.ACTION_UP:
					if (audioOptions.getBoolean("musicOn", true)) {
						audioEditor.putBoolean("musicOn", false);
						if (resourcesManager.musicGame.isPlaying())
							resourcesManager.musicGame.pause();
						AlphaModifier mod = new AlphaModifier(0.3f, 1, 0);
						AlphaModifier mod1 = new AlphaModifier(0.01f, 0, 1);
						this.registerEntityModifier(new SequenceEntityModifier(
								mod, mod1));
						index = 1;
						this.registerUpdateHandler(new TimerHandler(0.3f,
								new ITimerCallback() {
 
									@Override
									public void onTimePassed(
											TimerHandler pTimerHandler) {
										music.setCurrentTileIndex(index);
									}
								}));

					} else {
						audioEditor.putBoolean("musicOn", true);
						if (!resourcesManager.musicGame.isPlaying())
							resourcesManager.musicGame.play();
						else
						resourcesManager.musicGame.resume();

						AlphaModifier mod = new AlphaModifier(0.3f, 1, 0);
						AlphaModifier mod1 = new AlphaModifier(0.0001f, 0, 1);
						this.registerEntityModifier(new SequenceEntityModifier(
								mod, mod1));
						index = 0;

						this.registerUpdateHandler(new TimerHandler(0.3f,
								new ITimerCallback() {

									@Override
									public void onTimePassed(
											TimerHandler pTimerHandler) {
										music.setCurrentTileIndex(index);
									}
								})); 
					}
					audioEditor.commit();

					break;
				}
				return true;
			}
		};
		music.setCurrentTileIndex(index);
		sound = new TiledSprite(480, 13, 50, 40,
				resourcesManager.mTiledTextureRegionSound, vbom) {
			@Override
			public boolean onAreaTouched(
					final org.andengine.input.touch.TouchEvent pAreaTouchEvent,
					final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
				switch (pAreaTouchEvent.getAction()) {
				case org.andengine.input.touch.TouchEvent.ACTION_DOWN:
					break;
				case org.andengine.input.touch.TouchEvent.ACTION_UP:
					if (audioOptions.getBoolean("effectsOn", true)) {
						audioEditor.putBoolean("effectsOn", false);
						AlphaModifier mod = new AlphaModifier(0.3f, 1, 0);
						AlphaModifier mod1 = new AlphaModifier(0.0001f, 0, 1);
						this.registerEntityModifier(new SequenceEntityModifier(
								mod, mod1));
						indexS = 1;
						this.registerEntityModifier(mod);
						this.registerUpdateHandler(new TimerHandler(0.3f,
								new ITimerCallback() {

									@Override
									public void onTimePassed(
											TimerHandler pTimerHandler) {
										sound.setCurrentTileIndex(indexS);
									}
								}));
					} else {
						audioEditor.putBoolean("effectsOn", true);
						AlphaModifier mod = new AlphaModifier(0.3f, 1, 0);
						AlphaModifier mod1 = new AlphaModifier(0.0001f, 0, 1);
						this.registerEntityModifier(new SequenceEntityModifier(
								mod, mod1));
						indexS = 0;
						this.registerUpdateHandler(new TimerHandler(0.3f,
								new ITimerCallback() {

									@Override
									public void onTimePassed(
											TimerHandler pTimerHandler) {
										sound.setCurrentTileIndex(indexS);
									}
								}));
					}
					audioEditor.commit();

					break;
				}
				return true;
			}
		};
		sound.setCurrentTileIndex(indexS);
		this.attachChild(music);
		this.attachChild(sound);
		this.registerTouchArea(music);
		this.registerTouchArea(sound);
		this.setTouchAreaBindingOnActionDownEnabled(true);
		
	}

	int index = 0;
	int indexS = 0;
	int x1x = 590, x1y = 10;
	int x2x = 620, x2y = 7;
	int x3x = 658, x3y = 13;

	TiledSprite sound;
	TiledSprite music;

	public class MyCount extends CountDownTimer {

		public MyCount(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
		}
 
		public void onFinish() {

		}

		public void onTick(long millisUntilFinished) {
			Random r = new Random();
			int count = r.nextInt(5) + 2;
			for (int i = 0; i < count; i++) {
				addText();
			}
		}
	}

	private void createScore() {
		text = new Text(0, 0, resourcesManager.font, "0", 100, vbom);
		text.setColor(org.andengine.util.color.Color.YELLOW);
		text.setPosition(35, -35);
		text.setVisible(true);
		MoveYModifier move=new MoveYModifier(1f, text.getY(), 10){

			@Override
			protected void onModifierFinished(IEntity pItem) {
				// TODO Auto-generated method stub
				super.onModifierFinished(pItem);
				new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						setTextChange();
					}
				}.run();
				
			}
			
		};
		text.registerEntityModifier(move);
		this.attachChild(text);
		
		
		textx2 = new Text(0, 0, resourcesManager.fonttextx2, "0", 100, vbom);
		textx2.setColor(org.andengine.util.color.Color.GREEN);
		//textx2.setText(scorex2);
		//textx2.setPosition(50, 20);
		textx2.setVisible(false);
		
	}

	public Sprite backGroundSprite;
	private void createBackground() {
		backGroundSprite = new Sprite(0, 0, activity.CAMERA_WIDTH + 1,
				activity.CAMERA_HEIGHT + 1,
				resourcesManager.game_background_region, vbom);
		attachChild(backGroundSprite);
	}
	public void pauseGame() {
		this.setChildScene(mPauseScene, false, false, false);
		engine.stop();
	}
	public void unPauseGame() {
		this.clearChildScene();
		engine.start();
	}
	public class PauseableTimerHandler extends TimerHandler {
		 
		 public boolean mPause = false;
		  
		 public PauseableTimerHandler(float pTimerSeconds, boolean pAutoReset,
		   ITimerCallback pTimerCallback) {
		  super(pTimerSeconds, pAutoReset, pTimerCallback);
		 }
		  
		 public void pause() {
		  this.mPause = true;
		 }
		  
		 public void resume() {
		  this.mPause = false;
		 }
		 
		 @Override
		 public void onUpdate(float pSecondsElapsed) {
		  if(!this.mPause) {
		   super.onUpdate(pSecondsElapsed);
		  }
		 }
		}
	@Override
	public void onBackKeyPressed() {
		Log.d("nutback","nutback");
		if (en%2==0) {
			Log.d("nutback","nutback1");
			t.mPause =true;
			timer.mPause = true;
			timer1.mPause = true;
			timer2.mPause =true;
			timer3.mPause =true;
			timer4.mPause = true;
			timer5.mPause = true;
			timer6.mPause = true;
			timer7.mPause =true;
			timer8.mPause = true;
			timer9.mPause = true;
			timer10.mPause = true;
			timer11.mPause = true;
			timer12.mPause = true;
			timer13.mPause = true;
			//backGroundSprite.setAlpha(0.5f);
			//loadPauseSprite();
			/*pausedSprite.setPosition(-105, (float)y);
			restartSprite.setPosition(activity.CAMERA_WIDTH+5, y);
			quitSprite.setPosition(xQuit, yQuit);
			titleGame.setPosition(camera.getWidth()/2-resourcesManager.titlepausegame_region.getWidth()/2,-30);*/
		/*	mPauseScene.attachChild(pausedSprite);
			mPauseScene.attachChild(restartSprite);
			mPauseScene.attachChild(quitSprite);
			mPauseScene.attachChild(titleGame);*/
			
			getGameScene().setChildScene(mPauseScene, false, true, true);
			
			Log.d("pos","pauseGame");
			//pauseGame();
		//	engine.stop();
		//	this.setChildScene(pauseScene(), false,true,true);
		} else {
		//	engine.start();
			t.mPause =false;
			timer.mPause = false;
			timer1.mPause = false;
			timer2.mPause = false;
			timer3.mPause = false;
			timer4.mPause = false;
			timer5.mPause =false;
			timer6.mPause = false;
			timer7.mPause = false;
			timer8.mPause = false;
			timer9.mPause = false;
			timer10.mPause = false;
			timer11.mPause = false;
			timer12.mPause =false;
			timer13.mPause = false;
			//unloadPauseSprite();
			//backGroundSprite.setAlpha(1.0f);
			getGameScene().clearChildScene();
			
			Log.d("pos","unPauseGame");
		//	unPauseGame();		 
		}
		en++;
		//SceneManager.getInstance().loadMenuScene(engine);
		
	}
	public void unloadPauseSprite()
	{
		MoveXModifier movex=new MoveXModifier(0.3f, pausedSprite.getX(),-105);
		pausedSprite.registerEntityModifier(movex);
		
		MoveXModifier movex1=new MoveXModifier(0.3f, restartSprite.getX(), camera.getWidth()+10);
		restartSprite.registerEntityModifier(movex1);
		
		MoveYModifier movex2=new MoveYModifier(0.3f, quitSprite.getY(), camera.getHeight() + (resourcesManager.quitgame_region.getHeight()+10));
		quitSprite.registerEntityModifier(movex2);
	
		MoveYModifier move3=new MoveYModifier(0.5f, titleGame.getY(), -100);
		titleGame.registerEntityModifier(move3);
	}
	public void loadPauseSprite()
	{
		MoveXModifier movex=new MoveXModifier(0.3f, pausedSprite.getX(), camera.getWidth()/2-(pausedSprite.getWidth()+20));
		pausedSprite.registerEntityModifier(movex);

		MoveXModifier movex1=new MoveXModifier(0.3f, restartSprite.getX(), camera.getWidth()/2+20);
		restartSprite.registerEntityModifier(movex1);

		MoveYModifier movex2=new MoveYModifier(0.3f, quitSprite.getY(), camera.getHeight() - (resourcesManager.quitgame_region.getHeight()+10));
		quitSprite.registerEntityModifier(movex2);
		
		int y=(int) (camera.getHeight() / 2 - resourcesManager.mTiledTextureRegionPlay.getHeight() / 2);
		MoveYModifier move3=new MoveYModifier(0.5f, titleGame.getY(), y);
		titleGame.registerEntityModifier(move3);
	}
	int en = 0;
	private final int MENU_PLAY = 0;
	private final int MENU_RESTART = 1;
	MenuScene menuChildScene;
	Sprite blur;

	@Override
	protected void onManagedUpdate(float pSecondsElapsed) {
		// TODO Auto-generated method stub
		if(b){
			super.onManagedUpdate(0);			
		}
		else{
			super.onManagedUpdate(pSecondsElapsed);
		}
	}

	@Override
	public boolean onMenuItemClicked(MenuScene pMenuScene, IMenuItem pMenuItem,
			float pMenuItemLocalX, float pMenuItemLocalY) {
		// TODO Auto-generated method stub
		switch(pMenuItem.getID())
		{
		case MENU_PLAY:
			Log.d("pos","MENU_PLAY"+isPlay);
			//getGameScene().clearChildScene();
			engine.start();
			break;
		case MENU_RESTART: 
			if(!isPlay)
			{ 
				Log.d("pos","MENU_RESTART");
				SceneManager.getInstance().loadGameScene(engine);
				isPlay=true;
			}
			
			break;
		
		}
		/*switch(arg1.getID()){
		case 1:
			if(scene.hasChildScene()){
				scene.clearChildScene();
				pauseBtn.setVisible(true);
			}
			return true;
		default:
			return false;
		}*/
		return false;
	}
	
	
	
	@Override
	public SceneType getSceneType() {
		// TODO Auto-generated method stub
		return SceneType.SCENE_GAME;
	}

	@Override
	public void disposeScene() {
		camera.setHUD(null);
		camera.setChaseEntity(null); //TODO
		camera.setCenter(400, 240);

		// TODO code responsible for disposing scene
		// removing all game scene objects.

	}

	int xContinuos, k = 0;
	PhysicsWorld mPhysicsWorld;
	public void addText() {
		//resourcesManager.sliceWind.play();
		resourcesManager.playSoundWind();
		Log.d("addText", "addText");
		int maxX = activity.CAMERA_WIDTH/4*3-30;
		int minX = activity.CAMERA_WIDTH/4;
		int x1 = (int) (minX +Math.random()*((maxX-minX)+1));
		int maxY = activity.CAMERA_HEIGHT/2;
		int minY = activity.CAMERA_HEIGHT/4;
		int y0 = (int) (minY +Math.random()*((maxY-minX)+1));
		int y1 = activity.CAMERA_HEIGHT + 10;

		float rangX=(float) Math.random();
		float moveX= (rangX<0.4) ? 0.0f : rangX + 2f;
		float moveY =  SensorManager.GRAVITY_EARTH+5;
		float moveYdown =  SensorManager.GRAVITY_EARTH*5;
		float moveX0=0;
		final Fruit fruit;
		fruit = FruitPool.sharedFruitPool().onAllocatePoolItem();
		fruit.sprit.setPosition(x1, y1);

		// target.setVisible(true);
		// target.detachSelf();
		fruit.sprit.setVisible(true);
		fruit.sprit.detachSelf();
		attachChild(fruit.sprit);
		{
			fruitList.add(fruit);
		}
		fruitCount++;
		Log.d("fruitCount", fruitCount + "");
		mPhysicsWorld = new PhysicsWorld(new Vector2(0,
				-SensorManager.GRAVITY_EARTH), false);
		// synchronized (mPhysicsWorld)
		registerUpdateHandler(mPhysicsWorld); // side=0
		IsRun i = new IsRun();
		i.isRunUp = true;
		if (x1 <= activity.CAMERA_WIDTH / 2) {
			addFace(x1, y1, y0, mPhysicsWorld, i, fruit.sprit, 0,moveX,moveY,moveX0,moveYdown); // left->right
		} else {
			addFace(x1, y1, y0, mPhysicsWorld, i, fruit.sprit, 1,moveX,moveY,moveX0,moveYdown);// right->left
		}
		
	}
	public boolean sideTwo=true;
	public void addTwoSideText() {
		//resourcesManager.sliceWind.play();
		resourcesManager.playSoundWind();
		int maxX1 = activity.CAMERA_WIDTH/2;
		int minX1 = activity.CAMERA_WIDTH/4;
		int maxX2 = activity.CAMERA_WIDTH/4*3;
		int minX2 = maxX1;
		int x1;
		if(sideTwo){
			x1 = (int) (minX1 +Math.random()*((maxX1-minX1)+1));
			sideTwo=false;
		}
		else{
			x1 = (int) (minX2 +Math.random()*((maxX2-minX2)+1));
			sideTwo=true;
		}
		int y0 = (int) (50 +Math.random()*((activity.CAMERA_HEIGHT/2-50)+1));
		int y1 = activity.CAMERA_HEIGHT + 5;

		float rangX=(float) Math.random();
		float moveX =2.5f;
		float moveY = SensorManager.GRAVITY_EARTH;
		float moveYdown =  SensorManager.GRAVITY_EARTH*6;
		float moveX0=0;
		final Fruit fruit;
		fruit = FruitPool.sharedFruitPool().onAllocatePoolItem();
		fruit.sprit.setPosition(x1, y1);

		fruit.sprit.setVisible(true);
		fruit.sprit.detachSelf();
		attachChild(fruit.sprit);
		{
			fruitList.add(fruit);
		}
		fruitCount++;
		Log.d("fruitCount", fruitCount + "");
		mPhysicsWorld = new PhysicsWorld(new Vector2(0,
				-SensorManager.GRAVITY_EARTH), false);
		// synchronized (mPhysicsWorld)
		registerUpdateHandler(mPhysicsWorld); // side=0
		IsRun i = new IsRun();
		i.isRunUp = true;
		if (x1 <= activity.CAMERA_WIDTH / 2) {
			addFace(x1, y1, y0, mPhysicsWorld, i, fruit.sprit, 0,moveX,moveY,moveX0,moveYdown); // left->right
			Log.d("pos","addTwoSideText");
		} else {
			addFace(x1, y1, y0, mPhysicsWorld, i, fruit.sprit, 1,moveX,moveY,moveX0,moveYdown);// right->left
			Log.d("pos","addTwoSideText1");
		}
	}
	
	public void setTextScoreX2() {
		textx2.setText(scorex2);
	}
	
	public void setTextChange() {
		/*
		 * activity.runOnUpdateThread(new Runnable() {
		 * 
		 * @Override public void run() { // text.setPosition(160, 20);
		 * text.setText(score); } });
		 */
		text.setText(score);
		final float x = text.getX();
		final float y = text.getY();

		ScaleModifier sMod = new ScaleModifier(0.1f, 1f, 0.5f);
		ScaleModifier sMod1 = new ScaleModifier(0.1f, 0.5f, 1.6f);
		ScaleModifier sMod2 = new ScaleModifier(0.1f, 1.6f, 1f);
		float x1 = x;
		float y1 = y;
		MoveModifier mMod = new MoveModifier(0.1f, x1, x1 + 6, y1, y1 + 6);
		MoveModifier mMod1 = new MoveModifier(0.1f, text.getX(), x1 - 6,
				text.getY(), y1 + 6);
		MoveModifier mMod2 = new MoveModifier(0.1f, text.getX(), x1 + 6,
				text.getY(), y1 - 6);
		MoveModifier mMod3 = new MoveModifier(0.1f, text.getX(), x1 - 6,
				text.getY(), y1 - 6);

		// MoveModifier mMod4 = new MoveModifier(0.1f, mScene.text.getX(), y,
		// mScene.text.getY(), y);

		text.registerEntityModifier(new ParallelEntityModifier(
				new SequenceEntityModifier(mMod, mMod1, mMod2, mMod3),
				new SequenceEntityModifier(sMod, sMod1, sMod2)

		) {

			@Override
			public void onModifierFinished(IModifier<IEntity> pModifier,
					IEntity pItem) {
				// TODO Auto-generated method stub
				super.onModifierFinished(pModifier, pItem);
				text.setPosition(35, 10);
			}
		});
	}
	public void detach() {
		clearUpdateHandlers();
		for(Object b : fruitList) {
			 FruitPool.sharedFruitPool().onHandleRecycleItem((Fruit) b);
		}
		fruitList.clear();
	    detachChildren();
	    
	}
	PauseableTimerHandler _timerTextStagger;
    static int[] count_timerTextStagger;
  
	public void TimerTextStagger()
	{
		final Stagger s = new Stagger();
		s.count = 0;
		_timerTextStagger=new PauseableTimerHandler(0.1f, true, new ITimerCallback() {

			@Override
			public void onTimePassed(TimerHandler pTimerHandler) {
				// TODO Auto-generated method stub
				float rangX= (float) (15 + Math.random()*5f);
				final float moveX= rangX;
			    final float moveXdown = moveX-10;
				final float moveY= 5;
				final float scale_EARTH=4;
				addTextTwoBound(moveX, moveY,moveXdown,scale_EARTH);
				Log.d("stagger",count_timerTextStagger+":"+s.count);
				_timerTextStagger.setTimerSeconds(0.2f);
			//	 count_timerTextStagger[indexstagger++]++;
				s.count++; 
				if (s.count >= 15) {//6
					 unloadFrenzyImg();
							Log.d("stagger", "chay"+_timerTextStagger.getClass());
							_timerTextStagger.mPause = true;
							_timerTextStagger.setAutoReset(false);
							engine.unregisterUpdateHandler(_timerTextStagger);
				}
			}
			
		});
		engine.registerUpdateHandler(_timerTextStagger);
	}

	public void loadFrenzyImg()
	{
		MoveYModifier move=new MoveYModifier(0.5f, frenzy.getY(), 0);
		frenzy.registerEntityModifier(move);
	}
	public void unloadFrenzyImg()
	{
		MoveYModifier move=new MoveYModifier(0.5f, frenzy.getY(), -70);
		frenzy.registerEntityModifier(move);
	}
	
	public void loadFreezeImg()
	{
		MoveYModifier move=new MoveYModifier(0.5f, freeze.getY(), 0);
		freeze.registerEntityModifier(move);
	}
	public void unloadFreezeImg()
	{
		MoveYModifier move=new MoveYModifier(0.5f, freeze.getY(), -70);
		freeze.registerEntityModifier(move);
	}
	
}
